from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String

# 创建数据库引擎和会话
engine = create_engine('数据库连接字符串')
Session = sessionmaker(bind=engine)
session = Session()

Base = declarative_base()

# 定义数据模型
class Student(Base):
    __tablename__ = 'students'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    age = Column(Integer)

# 新增数据
def add_student(name, age):
    student = Student(name=name, age=age)
    session.add(student)
    session.commit()

# 修改数据
def update_student(id, name, age):
    student = session.query(Student).filter_by(id=id).first()
    if student:
        student.name = name
        student.age = age
        session.commit()

# 删除数据
def delete_student(id):
    student = session.query(Student).filter_by(id=id).first()
    if student:
        session.delete(student)
        session.commit()

# 查询数据
def query_students():
    students = session.query(Student).all()
    for student in students:
        print(f"ID: {student.id}, Name: {student.name}, Age: {student.age}")

# 示例用法
add_student("Alice", 20)
add_student("Bob", 22)
query_students()

update_student(1, "Charlie", 21)
delete_student(2)
query_students()
